package com.eda;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.Spinner;

import com.eda.common.ValueConvert;
import com.eda.db.DatabaseHelper;

public class OwnerPublishActivity extends Activity {

	/* 定义页面元素 */
	EditText contact;
	EditText start;
	EditText end;
	EditText truck;
	EditText weight;
	EditText size;
	EditText loadDate;

	Button publish;
	Button reset;
	Button datePicker;
	Button mytruck;

	final static int TRUCK = 1;
	final static int LOCATION = 2;
	final static int DATEPICKER = 3;

	EditText tempLocation;
	DatabaseHelper mOpenHelper;
	Spinner spprovince;
	Spinner spcity;
	Spinner sparea;
	SQLiteDatabase db;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_owner_publish_tab);

		mOpenHelper = new DatabaseHelper(this);
		db = mOpenHelper.getWritableDatabase();
		
		/* 元素初始化 */
		contact = (EditText) findViewById(R.id.ownerPubContact);
		start = (EditText) findViewById(R.id.ownerPubStart);
		end = (EditText) findViewById(R.id.ownerPubEnd);
		truck = (EditText) findViewById(R.id.ownerPubTruck);
		weight = (EditText) findViewById(R.id.ownerPubWeigth);
		size = (EditText) findViewById(R.id.ownerPubSize);
		loadDate = (EditText) findViewById(R.id.ownerPubLoadDate);

		publish = (Button) findViewById(R.id.ownerPubPublish);
		reset = (Button) findViewById(R.id.ownerPubReset);
		datePicker = (Button) findViewById(R.id.ownerPubDatePicker);
		mytruck = (Button) this.getParent().findViewById(R.id.commonFunction);
		
		/*按钮点击监听*/
		publish.setOnClickListener(publishListener);
		reset.setOnClickListener(resetListener);
		datePicker.setOnClickListener(datePickerListener);
		mytruck.setOnClickListener(datePickerListener);

		/* 绑定输入框点击事件 */
		start.setFocusable(false);
		start.setClickable(true);
		start.setInputType(InputType.TYPE_NULL);
		start.setOnClickListener(locationListener);

		end.setFocusable(false);
		end.setClickable(true);
		end.setInputType(InputType.TYPE_NULL);
		end.setOnClickListener(locationListener);

		truck.setFocusable(false);
		truck.setClickable(true);
		truck.setInputType(InputType.TYPE_NULL);
		truck.setOnClickListener(truckListener);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.owner_publish, menu);
		return true;
	}

	// 发布事件
	OnClickListener publishListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			SharedPreferences loginInfo = getSharedPreferences("LOGGING_INFO",0);
			String name = loginInfo.getString("USER_NAME", "");

			String url = ValueConvert.URL+"/pubTruck.do?userId="+name+
					"&contact="+contact.getText().toString()+
					"&start="+start.getText().toString()+
					"&end="+end.getText().toString()+
					"&truck="+truck.getText().toString()+
					"&weight="+weight.getText().toString()+
					"&size="+size.getText().toString()+
					"&loadDate="+loadDate.getText().toString();
			
			HttpClient client = new DefaultHttpClient();
			HttpPost request;
			try {
				request = new HttpPost(new URI(url));
				
				HttpParams params=client.getParams(); //计算网络超时用. 
				HttpConnectionParams.setConnectionTimeout(params, 3000);
				HttpConnectionParams.setSoTimeout(params, 5000);
				
				HttpResponse response = client.execute(request);
				// 判断请求是否成功
				if (response.getStatusLine().getStatusCode() == 200) {
					HttpEntity entity = response.getEntity();
					if (entity != null) {
						String out = EntityUtils.toString(entity);
						if(out!=null){
							
							if(ValueConvert.convert(out).get(0).get(0).equals("success")){
								new AlertDialog.Builder(OwnerPublishActivity.this).setMessage("发布成功").create().show();
							}else{
								new AlertDialog.Builder(OwnerPublishActivity.this).setMessage("发布失败").create().show();
							}
						}
					}
				}
			} catch (Exception e) {
				new AlertDialog.Builder(OwnerPublishActivity.this).setMessage("发布失败").create().show();
			} 
		}
	};

	// 重置监听
	OnClickListener resetListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			contact.setText("");
			start.setText("");
			end.setText("");
			truck.setText("");
			weight.setText("");
			size.setText("");
			loadDate.setText("");
		}
	};

	// 时间选择监听
	OnClickListener datePickerListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			showDialog(DATEPICKER);
		}
	};

	// 我的车辆监听
	OnClickListener mytruckListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			
		}
	};

	// 地点击监听
	OnClickListener locationListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			tempLocation = (EditText) arg0;
			showDialog(LOCATION);
		}
	};


	// 车辆点击监听
	OnClickListener truckListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			tempLocation = (EditText) arg0;
			showDialog(TRUCK);
		}
	};

	/* 地点选择框，车辆选择框 */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case LOCATION:
			return buildProviceDialog(OwnerPublishActivity.this);
		case TRUCK:
			return buildTypeDialog(OwnerPublishActivity.this);
		case DATEPICKER:
			return buildDateDialog(OwnerPublishActivity.this);
		default:
			return null;

		}
	}

	// 地区选择弹出框
	private Dialog buildProviceDialog(Context context) {

		LayoutInflater inflater = LayoutInflater.from(this);
		final View provinceView = inflater.inflate(R.layout.location_layout,
				null);
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setView(provinceView);
		builder.setTitle(R.string.alert_dialog_text_entry);

		spprovince = (Spinner) provinceView.findViewById(R.id.spprovince);
		spcity = (Spinner) provinceView.findViewById(R.id.spcity);
		sparea = (Spinner) provinceView.findViewById(R.id.sparea);

		String[] col = { "cityName" };
		Cursor cur = db.query("province", col, "parentid=0", null, null, null,
				null);

		List<String> provinceList = new ArrayList<String>();
		while (cur.moveToNext()) {
			provinceList.add(cur.getString(0));
		}
		ArrayAdapter provinceAdapter = new ArrayAdapter(
				OwnerPublishActivity.this,
				android.R.layout.simple_spinner_item, provinceList);
		provinceAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // 样式
		spprovince.setAdapter(provinceAdapter);
		spprovince.setOnItemSelectedListener(provinceSelectedListener);

		builder.setPositiveButton(R.string.alert_dialog_ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {

					}
				});

		builder.setNegativeButton(R.string.alert_dialog_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						tempLocation.setText("");
					}
				});

		return builder.create();
	}

	// 选择省事件
	private OnItemSelectedListener provinceSelectedListener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			try {
				Spinner spProvince = (Spinner) parent;
				String selectedProvince = (String) spProvince
						.getItemAtPosition(position);
				ArrayAdapter cityAdapter = null;

				String[] col = { "codeid", "cityName" };
				Cursor cur = db.query("province", col, "cityName='"
						+ selectedProvince + "'", null, null, null, null);
				int pid = -1;
				if (cur.moveToNext()) {
					pid = cur.getInt(0);// 得到省份的id
				}

				cur = db.query("province", col, "parentid=" + pid, null, null,
						null, null);

				List<String> cityList = new ArrayList<String>();
				while (cur.moveToNext()) {
					cityList.add(cur.getString(1));
				}
				cityAdapter = new ArrayAdapter(OwnerPublishActivity.this,
						android.R.layout.simple_spinner_item, cityList);
				cityAdapter
						.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spcity.setAdapter(cityAdapter);
				spcity.setOnItemSelectedListener(citySelectedListener);
			} catch (Exception e) {
				Log.d("WineStock", "Select Province error:" + e.getMessage());
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			// TODO Auto-generated method stub
		}
	};

	// 选择市事件
	private OnItemSelectedListener citySelectedListener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			try {
				Spinner spCity = (Spinner) parent;
				String selectedCity = (String) spCity
						.getItemAtPosition(position);
				ArrayAdapter areaAdapter = null;

				String[] col = { "codeid", "cityName" };
				Cursor cur = db.query("province", col, "cityName='"
						+ selectedCity + "'", null, null, null, null);
				int pid = -1;
				if (cur.moveToNext()) {
					pid = cur.getInt(0);// 得到省份的id
				}

				cur = db.query("province", col, "parentid=" + pid, null, null,
						null, null);

				List<String> areaList = new ArrayList<String>();
				while (cur.moveToNext()) {
					areaList.add(cur.getString(1));
				}
				areaAdapter = new ArrayAdapter(OwnerPublishActivity.this,
						android.R.layout.simple_spinner_item, areaList);
				areaAdapter
						.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				sparea.setAdapter(areaAdapter);
				sparea.setOnItemSelectedListener(areaSelectedListener);
			} catch (Exception e) {
				Log.d("WineStock", "Select Province error:" + e.getMessage());
			}
		}

		private OnItemSelectedListener citySelectedListener = new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					Spinner spCity = (Spinner) parent;
					String selectedCity = (String) spCity
							.getItemAtPosition(position);
					ArrayAdapter areaAdapter = null;

					String[] col = { "codeid", "cityName" };
					Cursor cur = db.query("province", col,
							"cityName='selectedProvince'", null, null, null,
							null);
					int pid = -1;
					if (cur.moveToNext()) {
						pid = cur.getInt(0);// 得到省份的id
					}

					cur = db.query("province", col, "parentid=" + pid, null,
							null, null, null);

					List<String> areaList = new ArrayList<String>();
					if (cur.moveToNext()) {
						areaList.add(cur.getString(1));
					}
					areaAdapter = new ArrayAdapter(OwnerPublishActivity.this,
							android.R.layout.simple_spinner_item, areaList);
					areaAdapter
							.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					sparea.setAdapter(areaAdapter);
					sparea.setOnItemSelectedListener(areaSelectedListener);
				} catch (Exception e) {
					Log.d("WineStock",
							"Select Province error:" + e.getMessage());
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
			}
		};

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			// TODO Auto-generated method stub
		}
	};

	// 选择区事件
	private OnItemSelectedListener areaSelectedListener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {

			Spinner spArea = (Spinner) parent;
			String selectedCity = (String) spArea.getItemAtPosition(position);
			tempLocation.setText(selectedCity);
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			// TODO Auto-generated method stub
		}
	};

	// 车型选择弹出框
	private Dialog buildTypeDialog(Context context) {

		LayoutInflater inflater = LayoutInflater.from(this);
		final View provinceView = inflater.inflate(R.layout.location_layout,
				null);
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setView(provinceView);
		builder.setTitle(R.string.alert_dialog_text_entry);

		spprovince = (Spinner) provinceView.findViewById(R.id.spprovince);

		/*查询我的车辆*/
		SharedPreferences loginInfo = getSharedPreferences("LOGGING_INFO", 0);
		String name = loginInfo.getString("USER_NAME", "");
		String url = ValueConvert.URL + "/myTruck.do?userId=" + name;

		HttpClient client = new DefaultHttpClient();
		HttpPost request;
		try {
			request = new HttpPost(new URI(url));

			HttpParams params = client.getParams(); // 计算网络超时用.
			HttpConnectionParams.setConnectionTimeout(params, 3000);
			HttpConnectionParams.setSoTimeout(params, 5000);

			HttpResponse response = client.execute(request);
			// 判断请求是否成功
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String out = EntityUtils.toString(entity);
					List<List<String>> data = ValueConvert.convert(out);
					if (out != null) {
						// List<Map<String, Object>> convertedData;
						List<String> truckList = new ArrayList<String>();
						for (List<String> line : data) {
							truckList.add(line.get(1)+"|"+line.get(2)+"|"+line.get(3));
						}

						ArrayAdapter provinceAdapter = new ArrayAdapter(OwnerPublishActivity.this, android.R.layout.simple_spinner_item, truckList);
						provinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // 样式
					    spprovince.setAdapter(provinceAdapter);
					    spprovince.setOnItemSelectedListener(typeSelectedListener);
					}
				}
			}
		} catch (Exception e) {
			new AlertDialog.Builder(OwnerPublishActivity.this)
					.setMessage("发布失败").create().show();
		}

		builder.setPositiveButton(R.string.alert_dialog_ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {

					}
				});

		builder.setNegativeButton(R.string.alert_dialog_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						tempLocation.setText("");
					}
				});

		return builder.create();
	}

	// 车辆选择事件
	private OnItemSelectedListener typeSelectedListener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {

			Spinner spType = (Spinner) parent;
			String type = (String) spType.getItemAtPosition(position);
			tempLocation.setText(type);
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			// TODO Auto-generated method stub
		}
	};

	// 日期选择弹出框
	private Dialog buildDateDialog(Context context) {

		LayoutInflater inflater = LayoutInflater.from(this);
		final View datePickerView = inflater.inflate(
				R.layout.activity_date_pick, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setView(datePickerView);
		builder.setTitle(R.string.alert_dialog_text_entry);

		DatePicker dp = (DatePicker) datePickerView
				.findViewById(R.id.date_picker);
		dp.init(2000, 1, 1, dateChangeListener);

		builder.setPositiveButton(R.string.alert_dialog_ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {

					}
				});

		builder.setNegativeButton(R.string.alert_dialog_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						loadDate.setText("");
					}
				});

		return builder.create();
	}

	OnDateChangedListener dateChangeListener = new OnDateChangedListener() {

		@Override
		public void onDateChanged(DatePicker arg0, int arg1, int arg2, int arg3) {
			loadDate.setText(arg1 + "年" + (arg2 + 1) + "月" + arg3 + "日");

		}
	};
}
